package com.java.servlet.web.login.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.java.servlet.web.commons.PropertiesUtils;
import com.java.servlet.web.login.service.LoginService;
import com.java.servlet.web.login.service.LoginServiceImpl;
import com.java.servlet.web.login.vo.LoginVo;
import com.java.servlet.web.menu.service.MenuService;
import com.java.servlet.web.menu.service.MenuServiceImpl;
import com.java.servlet.web.menu.vo.MenuVo;
import com.java.servlet.web.usuarios.vo.UsuariosVo;

/**
 * Servlet implementation class LoginController
 */
@WebServlet (name = "LoginController", urlPatterns="/login/loginController")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(LoginController.class);
	private static final int INIT_LOGIN = 0;
	private static final int LOGIN_USER = 1;
	private static final int VALIDAR_REGS = 2;
	private Properties viewConfig;
	private Properties fieldConfig;
    protected LoginService loginService;
    protected MenuService menuService;
	private StringBuffer stb;
	private List<MenuVo> listaSub = null;
	private List<MenuVo> listaSubUno = null;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
	public LoginController(){
	}
    public void init() {
		try {
			super.init();
			loginService = new LoginServiceImpl();
			menuService = new MenuServiceImpl();
			viewConfig = PropertiesUtils.getPropertiesFromFile(getServletContext().getResource("/WEB-INF/view-config.properties"));
			fieldConfig = PropertiesUtils.getPropertiesFromFile(getServletContext().getResource("/WEB-INF/form-config.properties"));
		} catch (MalformedURLException ex) {
			log.info("Error fatal, no se puedo cargar el archivo de configuracion de vistas." + ex);
		} catch(ServletException serEx){
			log.info("Error fatal, no se puedo cargar el archivo de configuracion de vistas." + serEx);
		}
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
		int metodo = Integer.parseInt(request.getParameter("method"));
		RequestDispatcher dispatcher = null;
		try {
			switch (metodo) {
			case INIT_LOGIN:
				dispatcher = request.getRequestDispatcher(viewConfig.getProperty("users.starter"));
				dispatcher.forward(request, response);
				break;
			case LOGIN_USER:
				String cadena = null;
			 	LoginVo loginUser = getLoginFromRequest(request);
			 	if(loginUser == null){
			 		dispatcher = request.getRequestDispatcher(viewConfig.getProperty("users.starter"));
			 		request.setAttribute("errUser", fieldConfig.getProperty("form.usuario.validar.user"));
			 		request.setAttribute("errPass", fieldConfig.getProperty("form.usuario.validar.password"));
					dispatcher.forward(request, response);
			 	} else{
					if (loginService.isEsisteUsuario(loginUser)) {
							UsuariosVo userVo = loginService.datosUsuario(loginUser);
							List<MenuVo> listaMenu = menuService.getMenuUsuario(userVo.getIdRol());
							String infoPath [] = request.getRequestURI().split("/");
							String pathApp = infoPath[1];
							cadena = generarMenuUsuario(listaMenu, pathApp);
							HttpSession sessionApp = request.getSession(true);
							sessionApp.setAttribute("auth", true);
							sessionApp.setAttribute("user", userVo.getNomUsuario());
							sessionApp.setAttribute("idRol", userVo.getIdRol());
							sessionApp.setAttribute("rol", userVo.getDescRol());
							sessionApp.setAttribute("cadena",cadena); 
							log.info("cadena    [  " + cadena);
							dispatcher = request.getRequestDispatcher(viewConfig.getProperty("system.inicio"));
						    dispatcher.forward(request, response);
					} else {
					 		dispatcher = request.getRequestDispatcher(viewConfig.getProperty("users.starter"));
					 		request.setAttribute("errPassUser", fieldConfig.getProperty("form.usuario.validar.userpass"));
							dispatcher.forward(request, response);
			 		}
			 	}
				break;
			case VALIDAR_REGS:

				break;
			}
		} catch (Exception e) {
			request.setAttribute("ex", e);
            dispatcher = request.getRequestDispatcher(viewConfig.getProperty("error"));
            dispatcher.forward(request, response);
			System.out.println("Error en LoginController " + e);
			e.printStackTrace();
		} finally {
            out.close();
        }
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
    private LoginVo getLoginFromRequest(HttpServletRequest request) {
    	LoginVo login = new LoginVo();
            if (StringUtils.isNotBlank(request.getParameter(fieldConfig.getProperty("form.usuario.user")))) {
                login.setUser(String.valueOf(request.getParameter(fieldConfig.getProperty("form.usuario.user"))));
            } else {
            	login = null;
            }
            if (StringUtils.isNotBlank(request.getParameter(fieldConfig.getProperty("form.usuario.password")))) {
                login.setPassword(String.valueOf(request.getParameter(fieldConfig.getProperty("form.usuario.password"))));
            } else{
            	login = null;
            }
        return login;
    }
    /*
    private String generarMenuUsuario(List<MenuVo> listaMenu, String pathInfo){
    	stb.append("<ul class='nav'>");
    	for(MenuVo menuPadre : listaMenu){
    		listaSub = new ArrayList<MenuVo>();
    		if(menuPadre.getIdParent() == 0 && menuPadre.equals("menu")){
    			stb.append("<li>");
				stb.append("<a");
				if(menuPadre.getLink() != null && !menuPadre.getLink().equals("")){
					stb.append(" href='").append("/").append(pathInfo).append(menuPadre.getLink()).append("'");
				}
				stb.append(">");
				stb.append(menuPadre.getDescMenu()).append("</a>");
				System.out.println("stb.toString  [   " + stb.toString());
				for(MenuVo menuSub: listaMenu){
					if(menuPadre.getIdMenu() == menuSub.getIdParent()){
						listaSub.add(menuSub);
					}
				}
    		} else{
    			if(menuPadre.getIdParent() != 0 && !menuPadre.equals("menu")){
    			generarMenuUsuario(listaSub,pathInfo);
    			}
    		}
				stb.append("</li>");
    	}
    	stb.append("</ul>");
    	return stb.toString();
    }
    */
	
	private String generarMenuUsuario(List<MenuVo> listaMenu, String pathInfo) {
		stb = new StringBuffer();
		stb.append("<ul class='nav'>");
		for (MenuVo obj : listaMenu) {
			listaSub = new ArrayList<MenuVo>();
			if(obj.getIdParent() == 0 && obj.getParent().equals("menu")){
				stb.append("<li>");
				stb.append("<a");
				if(obj.getLink() != null && !obj.getLink().equals("")){
					stb.append(" href='").append("/").append(pathInfo).append(obj.getLink()).append("'");
				}
				stb.append(">");
				
				stb.append(obj.getDescMenu()).append("</a>");
					for(MenuVo menu : listaMenu){
						if(obj.getIdMenu() == menu.getIdParent()){
							listaSub.add(menu);
							
						}
					}
					if(listaSub.size() > 0){
						stb.append("<ul>");
						for(MenuVo subMenu : listaSub){
							listaSubUno = new ArrayList<MenuVo>();
							stb.append("<li>").append("<a");
							if(subMenu.getLink() != null && !subMenu.getLink().equals("")){
								stb.append(" href='").append("/").append(pathInfo).append(subMenu.getLink()).append("'");
							}
							stb.append(">");
							stb.append(subMenu.getDescMenu()).append("</a>");
							for(MenuVo menuNvl : listaMenu){
								if(subMenu.getIdMenu() == menuNvl.getIdParent()){
									listaSubUno.add(menuNvl);
									
								}
							}
							if(listaSubUno.size() > 0){
								stb.append("<ul>");
								for(MenuVo subMenuNvl : listaSubUno){
									stb.append("<li>").append("<a");
									if(subMenu.getLink() != null && !subMenu.getLink().equals("")){
										stb.append(" href='").append("/").append(pathInfo).append(subMenuNvl.getLink()).append("'");
									}
									stb.append(">");
									stb.append(subMenuNvl.getDescMenu()).append("</a>").append("</li>");
								}
								stb.append("</ul>");
							}
							stb.append("</li>");
						}
						stb.append("</ul>");
					}
				stb.append("</li>");
			} else {
				
			}
			
		}
		stb.append("</ul>");
		return stb.toString();
	}
		
}
